import 'package:get/get.dart';
import 'modal.dart';

class PullRefreshController<T> extends GetxController {
  final int pageSize;
  int pageCount;
  int _total = 0;

  final RxList<T> dataList = <T>[].obs;
  final RxBool isRefreshing = false.obs;
  final RxBool isLoadingMore = false.obs;
  final Future<ListResponse<T>> Function(int pageCount, int pageSize) fetchData;

  PullRefreshController({
    required this.fetchData,
    required this.pageSize,
    required this.pageCount,
  });

  /// 初始化数据（首次加载）
  void initData() async {
    if (dataList.isEmpty && !isRefreshing.value) {
      await refreshData();
    }
  }

  /// 下拉刷新（重置页码）
  Future<void> refreshData() async {
    if (isRefreshing.value) return;

    isRefreshing.value = true;
    pageCount = 1;

    try {
      final response = await fetchData(pageCount, pageSize);
      _total = response.total;
      dataList
        ..clear()
        ..addAll(response.data);
    } catch (e) {
      Get.rawSnackbar(
        title: '刷新失败',
        message: e.toString(),
        duration: const Duration(seconds: 2),
      );
    } finally {
      isRefreshing.value = false;
    }
  }

  /// 上拉加载更多（页码自增）
  Future<void> loadMoreData() async {
    if (isLoadingMore.value || dataList.length >= _total) return;

    isLoadingMore.value = true;
    pageCount++;

    try {
      final response = await fetchData(pageCount, pageSize);
      _total = response.total;
      dataList.addAll(response.data);
    } catch (e) {
      pageCount--;
      Get.rawSnackbar(
        title: '加载更多失败',
        message: e.toString(),
        duration: const Duration(seconds: 2),
      );
    } finally {
      isLoadingMore.value = false;
    }
  }

  /// 判断是否还有更多数据
  bool get hasMoreData => dataList.length < _total;
}